package com.eee.xiang.market.configuration;

import com.eee.xiang.market.utils.ApplicationUtil;
import org.apache.ibatis.cache.Cache;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class MyBatisRedisCache implements Cache {

    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);
    private RedisTemplate dbRedis = ApplicationUtil.getBean("dbRedisTemplate");
    private String id;

    public MyBatisRedisCache(String id) {
        if(id == null){
            throw new IllegalArgumentException("Cache requied an ID");
        }
        this.id = id;
    }

    @Override
    public String getId() {
        return this.id;
    }

    @Override
    public void putObject(Object key, Object value) {
        if(value != null){
            dbRedis.opsForHash().put(id,key,value);
        }
    }

    @Override
    public Object getObject(Object key) {
        return dbRedis.opsForHash().get(id, key);
    }

    @Override
    public Object removeObject(Object key) {
        return dbRedis.opsForHash().delete(id, key);
    }

    @Override
    public void clear() {
        dbRedis.delete(id);
    }


    @Override
    public int getSize() {
        Long size = (Long) dbRedis.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                return connection.dbSize();
            }
        });
        return size.intValue();
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return this.readWriteLock;
    }
}
